﻿
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEngine;
using UnityEngine.AddressableAssets;

public class XBuildContentEditor {
    public const string resUpdatePath = "Assets/ResUpdate";
    public static string projectPath {
        get
        {
            return Application.dataPath.Replace("\\", "/").Replace("/Assets", "");
        }
    }

    public static string backupPathCatalogAndBundle
    {
        get
        {
            return projectPath + "/TempCatalogAndBundle/" + UnityEditor.EditorUserBuildSettings.activeBuildTarget + "/" + Application.version;
        }
    }

    public static string buildPath
    {

        get
        {
            return XBuildContentEditor.projectPath + "/" + Addressables.BuildPath + "/" + UnityEditor.EditorUserBuildSettings.activeBuildTarget;
        }
    }

    public static string buildCotentUpdatePath
    {
        get
        {

            AddressableAssetSettings setting = AddressableAssetSettingsDefaultObject.Settings;
            var id = setting.profileSettings.GetProfileId("Default");
            var path = setting.profileSettings.GetValueByName(id, "Remote.BuildPath");
            path = projectPath + "/" + setting.profileSettings.EvaluateString(id, path);
            return path;
        }
    }

    public static void MarkAddress()
    {
        HashSet<string> excludeGroups = new HashSet<string>() { "Built In Data", "Default Local Group" };
        var setting = AddressableAssetSettingsDefaultObject.Settings;

        //清除组
        List<AddressableAssetGroup> delGroups = new List<AddressableAssetGroup>();
        foreach (var delGroup in setting.groups)
        {

            if (!excludeGroups.Contains(delGroup.name))
            {
                delGroups.Add(delGroup);
            }
        }
        foreach (var delGroup in delGroups)
        {
            Debug.Log("delGroup :" + delGroup.name);
            setting.RemoveGroup(delGroup);
        }

        /*
            多组代码
 -         string resUpdateAssetPath = "Assets/ResUpdate/Asset";
 -         string texturePath = resUpdateAssetPath + "/" + XResType.Texture.ToString();
 -         string textAssetPath = resUpdateAssetPath + "/" + XResType.TextAsset.ToString();
 -         string prefabPath = "Assets/ResUpdate/Prefab";
 - 
 -         //Texture Group
 -         var group = CreateGroup(setting, "TextureGroup");
 -         var guids = AssetDatabase.FindAssets("t:texture t:sprite", new string[] { texturePath });
 -         CreateEntry(setting, group, guids);
 - 
 -         //TextAsset Group
 -         group = CreateGroup(setting, "TextAssetGroup");
 -         guids = AssetDatabase.FindAssets("t:textasset", new string[] { textAssetPath });
 -         CreateEntry(setting, group, guids);
 - 
 -         //Prefab Group
 -         group = CreateGroup(setting, "PrefabGroup");
 -         guids = AssetDatabase.FindAssets("t:prefab", new string[] { prefabPath });
 -         CreateEntry(setting, group, guids);

         */

        //直接用默认组。因为LZ4打包，支持流读取，不会因为加载一个资源，整个组加载进内存
        var defaultGroup = setting.DefaultGroup;

        //清除所有组里面所有的映射文件
        var entries = new List<AddressableAssetEntry>();
        entries.AddRange(defaultGroup.entries);
        for (int i = entries.Count - 1; i >= 0; i--)
        {
            defaultGroup.RemoveAssetEntry(entries[i]);
        }

        //枚举所有映射文件
        var guids = AssetDatabase.FindAssets("t:texture t:sprite t:textasset t:prefab t:audioclip", new string[] { resUpdatePath });

        //所有映射文件加入组
        CreateEntry(setting, defaultGroup, guids);
    }

    //private AddressableAssetGroup CreateGroup(AddressableAssetSettings setting, string groupName)
    //{
    //    var defaultGroup = setting.DefaultGroup;
    //    var group = setting.CreateGroup(groupName, false, false, false,
    //        new List<AddressableAssetGroupSchema>() { defaultGroup.Schemas[0], defaultGroup.Schemas[1] }//,
    //        //typeof(SchemaType)
    //        );
    //    return group;
    //}

    private static void CreateEntry(AddressableAssetSettings setting, AddressableAssetGroup group, string[] guids)
    {
        foreach (var guid in guids)
        {
            var entry = setting.CreateOrMoveEntry(guid, group);
            var assetPath = AssetDatabase.GUIDToAssetPath(guid);
            entry.address = Path.GetFileNameWithoutExtension(assetPath);
        }
    }

    public static void DefaultBuildScript()
    {
        UnityEditor.AddressableAssets.Settings.AddressableAssetSettings.BuildPlayerContent(out UnityEditor.AddressableAssets.Build.AddressablesPlayerBuildResult result);
        bool success = string.IsNullOrEmpty(result.Error);

        if (!success)
        {
            UnityEngine.Debug.LogError("Addressables build error encountered: " + result.Error);
        }
        else
        {
            //UnityEngine.Debug.LogError("Addressables build Success encountered: " + result.Error);
            BackupCatalogAndBundle();
        }
    }

    private static void BackupCatalogAndBundle()
    {
        //删除热更目录的文件
        if (Directory.Exists(buildCotentUpdatePath))
        {
            var files = Directory.GetFiles(buildCotentUpdatePath);
            foreach (var file in files)
            {
                Debug.Log("删除:" + file);
                File.Delete(file);
            }
        }

        //新建目录
        var backupPath = backupPathCatalogAndBundle;
        if (Directory.Exists(backupPath)) { 
            Directory.Delete(backupPath, true);
        }
        Directory.CreateDirectory(backupPath);


        //遍历文件
        var sourcePath = buildPath;
        var paths1 = Directory.GetFiles(sourcePath, "*.bundle");
        var paths2 = Directory.GetFiles(sourcePath, "*.hash");
        var paths3 = Directory.GetFiles(sourcePath, "*.json");
        List<string> paths = new List<string>();
        paths.AddRange(paths1);
        paths.AddRange(paths2);
        paths.AddRange(paths3);

        //开始备份
        foreach (var path in paths)
        {
            if (path.Contains("unitybuiltinshaders"))
                continue;
            string toPath = Path.Combine(backupPath, Path.GetFileName(path));
            Debug.Log("备份：" + path + " 到 " + toPath);
            File.Copy(path, toPath);
        }
    }

    public static void HandleContentGroup()
    {
        var setting = AddressableAssetSettingsDefaultObject.Settings;

        foreach (var group in setting.groups)
        {
            if(group.name.Contains("Content Update"))
            {
                foreach (var entry in group.entries)
                {
                    entry.SetLabel(XDownload.updateLabel, true);//Setting to true will add the label, false will remove it.
                }

                var bundledAssetGroupSchema = group.GetSchema<BundledAssetGroupSchema>();
                bundledAssetGroupSchema.BundleNaming = BundledAssetGroupSchema.BundleNamingStyle.NoHash;
            }
        }
     
    }

}